package com.dean.service.impl;

import com.dean.entity.DeanResponse;
import com.dean.exception.DeanRuntimeException;
import com.dean.service.support.AbstractDeanScriptService;
import com.dean.utils.FileUtils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dean
 * @version 1.0
 * @description: JavaScript脚本调用服务
 * @date 2024/1/31 11:01
 */
public class DeanJavaScriptService extends AbstractDeanScriptService {
    public DeanResponse call(String jscript, Map<String,Object> parameters) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");
        try {
            engine.eval(jscript);
            Invocable invocable = (Invocable) engine;
            Map<String,Object> params = init();
            params.putAll(parameters);
            Object result = invocable.invokeFunction("call",params);
            return DeanResponse.ok(result);
        } catch (ScriptException | NoSuchMethodException e) {
            DeanRuntimeException.throwException(996,e.getMessage(),e);
        }
        return DeanResponse.ok();
    }


//    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
//        String js = " function call (params) { " +
//                "       var sum = params['a'] + params['b'];  " +
//                "       return params;  " +
//                "}";
//        Map<String,Object> params =  new HashMap<>();
//        new DeanJavaScriptService().call(js,params);
//    }

}
